﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.ComponentModel;

namespace TA.Turbo.Controls
{
	/// <summary>
	/// Validates a control by making sure its value is not empty.
	/// </summary>
	public class RequiredValidator : BaseValidator
	{
		#region PUBLIC
		#region INIT
		/// <summary>
		/// Ctor.
		/// </summary>
		public RequiredValidator()
		{
			ValidateEmpty = true;
		}
		#endregion
		#region PROPS
		/// <summary>
		/// If true (default), will validate control if value not set.
		/// </summary>
		[DefaultValue(true)]
		public override bool ValidateEmpty
		{
			get
			{
				return base.ValidateEmpty;
			}
			set
			{
				base.ValidateEmpty = value;
			}
		}
		#endregion
		#endregion
		#region INTERNAL
		#region METHODS
		#region INIT
		/// <summary>
		/// Registers RequiredValidator.js.
		/// </summary>
		protected internal override void RegisterIncludes(IncludeCollection includes)
		{
			base.RegisterIncludes(includes);

			includes.Add(Script.String_IsNullOrEmpty);
			includes.Add(new ScriptResourceInclude("TA.Turbo.Res.JS.Validators.RequiredValidator.js", typeof(RequiredValidator)));
		}
		#endregion
		#region VALIDATION
		/// <summary>
		/// Checks if validated control's value is empty.
		/// </summary>
		protected override void DoValidate()
		{
			SetValidStatus(ValidatedControl.GenericValue != null && ValidatedControl.GenericValue.ToString() != "");
		}
		/// <summary>
		/// Uses IValueControlContainer to resolve all validated controls and their respective RequiredValidators.
		/// </summary>
		protected override void ResolveValidatedControl()
		{
			if (ValidatedControl == null)
			{
				if (ValidatedValueControlContainer != null)
				{
					if (ValidatedValueControlContainer.RequiredValidationFields.Any())
					{
						foreach (TControl c in ValidatedValueControlContainer.RequiredValidationFields.Skip(1))
						{
							RequiredValidator rv = new RequiredValidator
							{
								ID = this.ID + TControl.UniqueIdSeparator + c.ID,
								ValidatedControlId = c.UniqueID,
								InlineMessage = this.InlineMessage,
								SummaryMessage = this.SummaryMessage,
								Display = ValidatorDisplay.Dynamic,
							};
							this.Parent.Controls.AddAt(this.Parent.Controls.IndexOf(this) + 1, rv);
						}

						ValidatedControlId = ValidatedValueControlContainer.RequiredValidationFields.First().UniqueID;
						ResolveValidatedControl();
						return;
					}
				}
				else
					this.Controls.Remove(this);

			}
		}
		#endregion
		#endregion
		#endregion
	}
}
